// pages/book/book.js
import { Book } from '../../models/book.js'
import { Shopcart } from '../../models/shopcart.js'
var book = new Book()
var shopcart = new Shopcart("buyLocalShopcart")

Page({
  data: {
    book: {},
    price: 0,
    pickerIndex: 0,
    infoIndex: 0,
    pickerArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this._loadData(options.id)
  },

  _loadData(id) {
    book.showLoading()
    book.getBookDetail(id, (data) => {
      var price = Number(data.data.price) * Number(data.data.discount)
      price = price.toFixed(1)
      this.setData({
        book: data.data,
        price: price
      })
      wx.hideLoading()
    })
  },

  fullViewImg(event){
    wx.previewImage({
      urls: [event.currentTarget.dataset.src] // 需要预览的图片http链接列表
    })
  },

  // 选择 info tap
  onInfoTap: function(event) {
    this.setData({
      infoIndex: event.currentTarget.dataset.index
    })
  },

  onPickerChange: function(event) {
    var count = event.detail.value
    this.setData({
      pickerIndex: count
    })
  },

  toShopcart(){
    wx.switchTab({
      url: '/pages/shopcart/shopcart'
    })
  },

  addShopCart: function() {
    var index = this.data.pickerIndex
    var array = this.data.pickerArray

    // 加入的数量
    var num = array[index]

    // 这个价格已经修改了  
    // item.price = 要显示的价格  不用管 discount rate
    var item = book.getBaseInfo(this.data.book, true)

    shopcart.addToCart(item, num)
    shopcart.toast("加入购物车成功")
  }
})